
// src/main/java/com/xxxy/ljh/myapplication/DaoImpl/BorrowDaoImpl.java
package com.xxxy.ljh.myapplication.DaoImpl;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.xxxy.ljh.myapplication.Dao.BorrowDao;
import com.xxxy.ljh.myapplication.dphelper.sqliteDBHelper;
import com.xxxy.ljh.myapplication.model.BorrowRecord;

import java.util.ArrayList;
import java.util.List;

/**
 * 借阅数据访问接口实现类，提供借阅记录的增删改查功能。
 */
public class BorrowDaoImpl implements BorrowDao {

    private Context mContext;
    private SQLiteDatabase mDatabase;

    /**
     * 构造方法，初始化数据库连接。
     *
     * @param context 应用上下文对象
     */
    public BorrowDaoImpl(Context context) {
        mContext = context;
        mDatabase = new sqliteDBHelper(mContext).getWritableDatabase();
    }

    /**
     * 提交物品借用申请，并将记录插入到数据库中。
     *
     * @param borrowRecord 包含借阅信息的对象
     * @return 返回插入操作影响的行数，-1 表示失败
     */
    @Override
    public long requestBorrow(BorrowRecord borrowRecord) {
        ContentValues values = new ContentValues();
        values.put("item_id", borrowRecord.getItemId());
        values.put("user_id", borrowRecord.getUserId());
        values.put("association_id", borrowRecord.getAssociationId());
        values.put("borrow_quantity", borrowRecord.getBorrowQuantity());
        values.put("plan_return_time", borrowRecord.getPlanReturnTime());
        values.put("return_status", borrowRecord.getReturnStatus());
        values.put("checker_id", borrowRecord.getCheckerId());
        values.put("borrow_remark", borrowRecord.getBorrowRemark());

        long result = mDatabase.insert("item_borrow", null, values);
        return result;
    }

    /**
     * 归还指定ID的物品并更新相关字段。
     *
     * @param borrowId      借阅记录ID
     * @param returnRemark  归还备注信息
     * @return 操作是否成功（true 成功，false 失败）
     */
    @Override
    public boolean returnItem(int borrowId, String returnRemark) {
        ContentValues values = new ContentValues();
        values.put("actual_return_time", System.currentTimeMillis() + ""); // 当前时间
        values.put("return_status", 1); // 1表示已归还
        values.put("return_remark", returnRemark);

        String whereClause = "borrow_id = ?";
        String[] whereArgs = {String.valueOf(borrowId)};

        int result = mDatabase.update("item_borrow", values, whereClause, whereArgs);
        return result > 0;
    }

    /**
     * 根据用户ID查询该用户的全部借阅记录。
     *
     * @param userId 用户唯一标识符
     * @return 查询结果列表，每项为一个 BorrowRecord 对象
     */
    @Override
    public List<BorrowRecord> getBorrowRecordsByUserId(int userId) {
        String selection = "user_id = ?";
        String[] selectionArgs = {String.valueOf(userId)};
        Cursor cursor = mDatabase.query("item_borrow", null, selection, selectionArgs, null, null, null);

        List<BorrowRecord> records = new ArrayList<>();
        while (cursor.moveToNext()) {
            BorrowRecord record = new BorrowRecord();
            record.setBorrowId(cursor.getInt(cursor.getColumnIndexOrThrow("borrow_id")));
            record.setItemId(cursor.getInt(cursor.getColumnIndexOrThrow("item_id")));
            record.setUserId(cursor.getInt(cursor.getColumnIndexOrThrow("user_id")));
            record.setAssociationId(cursor.getInt(cursor.getColumnIndexOrThrow("association_id")));
            record.setBorrowQuantity(cursor.getInt(cursor.getColumnIndexOrThrow("borrow_quantity")));
            record.setBorrowTime(cursor.getString(cursor.getColumnIndexOrThrow("borrow_time")));
            record.setPlanReturnTime(cursor.getString(cursor.getColumnIndexOrThrow("plan_return_time")));
            record.setActualReturnTime(cursor.getString(cursor.getColumnIndexOrThrow("actual_return_time")));
            record.setReturnStatus(cursor.getInt(cursor.getColumnIndexOrThrow("return_status")));
            record.setCheckerId(cursor.getInt(cursor.getColumnIndexOrThrow("checker_id")));
            record.setBorrowRemark(cursor.getString(cursor.getColumnIndexOrThrow("borrow_remark")));
            record.setReturnRemark(cursor.getString(cursor.getColumnIndexOrThrow("return_remark")));
            records.add(record);
        }
        cursor.close();
        return records;
    }

    /**
     * 根据物品ID查询所有与之相关的借阅记录。
     *
     * @param itemId 物品唯一标识符
     * @return 查询结果列表，每项为一个 BorrowRecord 对象
     */
    @Override
    public List<BorrowRecord> getBorrowRecordsByItemId(int itemId) {
        String selection = "item_id = ?";
        String[] selectionArgs = {String.valueOf(itemId)};
        Cursor cursor = mDatabase.query("item_borrow", null, selection, selectionArgs, null, null, null);

        List<BorrowRecord> records = new ArrayList<>();
        while (cursor.moveToNext()) {
            BorrowRecord record = new BorrowRecord();
            record.setBorrowId(cursor.getInt(cursor.getColumnIndexOrThrow("borrow_id")));
            record.setItemId(cursor.getInt(cursor.getColumnIndexOrThrow("item_id")));
            record.setUserId(cursor.getInt(cursor.getColumnIndexOrThrow("user_id")));
            record.setAssociationId(cursor.getInt(cursor.getColumnIndexOrThrow("association_id")));
            record.setBorrowQuantity(cursor.getInt(cursor.getColumnIndexOrThrow("borrow_quantity")));
            record.setBorrowTime(cursor.getString(cursor.getColumnIndexOrThrow("borrow_time")));
            record.setPlanReturnTime(cursor.getString(cursor.getColumnIndexOrThrow("plan_return_time")));
            record.setActualReturnTime(cursor.getString(cursor.getColumnIndexOrThrow("actual_return_time")));
            record.setReturnStatus(cursor.getInt(cursor.getColumnIndexOrThrow("return_status")));
            record.setCheckerId(cursor.getInt(cursor.getColumnIndexOrThrow("checker_id")));
            record.setBorrowRemark(cursor.getString(cursor.getColumnIndexOrThrow("borrow_remark")));
            record.setReturnRemark(cursor.getString(cursor.getColumnIndexOrThrow("return_remark")));
            records.add(record);
        }
        cursor.close();
        return records;
    }

    /**
     * 根据借阅记录ID获取单条详细记录。
     *
     * @param borrowId 借阅记录唯一标识符
     * @return 若存在则返回对应的 BorrowRecord 实例，否则返回 null
     */
    @Override
    public BorrowRecord getBorrowRecordById(int borrowId) {
        String selection = "borrow_id = ?";
        String[] selectionArgs = {String.valueOf(borrowId)};
        Cursor cursor = mDatabase.query("item_borrow", null, selection, selectionArgs, null, null, null);

        BorrowRecord record = null;
        if (cursor.moveToFirst()) {
            record = new BorrowRecord();
            record.setBorrowId(cursor.getInt(cursor.getColumnIndexOrThrow("borrow_id")));
            record.setItemId(cursor.getInt(cursor.getColumnIndexOrThrow("item_id")));
            record.setUserId(cursor.getInt(cursor.getColumnIndexOrThrow("user_id")));
            record.setAssociationId(cursor.getInt(cursor.getColumnIndexOrThrow("association_id")));
            record.setBorrowQuantity(cursor.getInt(cursor.getColumnIndexOrThrow("borrow_quantity")));
            record.setBorrowTime(cursor.getString(cursor.getColumnIndexOrThrow("borrow_time")));
            record.setPlanReturnTime(cursor.getString(cursor.getColumnIndexOrThrow("plan_return_time")));
            record.setActualReturnTime(cursor.getString(cursor.getColumnIndexOrThrow("actual_return_time")));
            record.setReturnStatus(cursor.getInt(cursor.getColumnIndexOrThrow("return_status")));
            record.setCheckerId(cursor.getInt(cursor.getColumnIndexOrThrow("checker_id")));
            record.setBorrowRemark(cursor.getString(cursor.getColumnIndexOrThrow("borrow_remark")));
            record.setReturnRemark(cursor.getString(cursor.getColumnIndexOrThrow("return_remark")));
        }
        cursor.close();
        return record;
    }

    /**
     * 获取所有逾期未归还的借阅记录。
     *
     * @return 所有逾期记录组成的列表
     */
    @Override
    public List<BorrowRecord> getOverdueRecords() {
        // 查询条件：状态为未归还且计划归还时间早于当前时间
        String selection = "return_status = ? AND plan_return_time < datetime('now')";
        String[] selectionArgs = {"0"};
        Cursor cursor = mDatabase.query("item_borrow", null, selection, selectionArgs, null, null, null);

        List<BorrowRecord> records = new ArrayList<>();
        while (cursor.moveToNext()) {
            BorrowRecord record = new BorrowRecord();
            record.setBorrowId(cursor.getInt(cursor.getColumnIndexOrThrow("borrow_id")));
            record.setItemId(cursor.getInt(cursor.getColumnIndexOrThrow("item_id")));
            record.setUserId(cursor.getInt(cursor.getColumnIndexOrThrow("user_id")));
            record.setAssociationId(cursor.getInt(cursor.getColumnIndexOrThrow("association_id")));
            record.setBorrowQuantity(cursor.getInt(cursor.getColumnIndexOrThrow("borrow_quantity")));
            record.setBorrowTime(cursor.getString(cursor.getColumnIndexOrThrow("borrow_time")));
            record.setPlanReturnTime(cursor.getString(cursor.getColumnIndexOrThrow("plan_return_time")));
            record.setActualReturnTime(cursor.getString(cursor.getColumnIndexOrThrow("actual_return_time")));
            record.setReturnStatus(cursor.getInt(cursor.getColumnIndexOrThrow("return_status")));
            record.setCheckerId(cursor.getInt(cursor.getColumnIndexOrThrow("checker_id")));
            record.setBorrowRemark(cursor.getString(cursor.getColumnIndexOrThrow("borrow_remark")));
            record.setReturnRemark(cursor.getString(cursor.getColumnIndexOrThrow("return_remark")));
            records.add(record);
        }
        cursor.close();
        return records;
    }

    /**
     * 更新某条借阅记录的状态。
     *
     * @param borrowId 借阅记录ID
     * @param status   新的状态码（如 0: 未归还；1: 已归还）
     * @return 是否更新成功
     */
    @Override
    public boolean updateBorrowStatus(int borrowId, int status) {
        ContentValues values = new ContentValues();
        values.put("return_status", status);

        String whereClause = "borrow_id = ?";
        String[] whereArgs = {String.valueOf(borrowId)};

        int result = mDatabase.update("item_borrow", values, whereClause, whereArgs);
        return result > 0;
    }
}